#!/usr/bin/env python3
import os
import sys

from middlewared.client import Client

with Client() as c:
    s3 = c.call("s3.config")

    if not os.path.isdir(s3["storage_path"]):
        sys.stderr.write(f'{s3["storage_path"]} does not exist or is not a directory\n')
        sys.exit(1)

    os.chown(
        s3["storage_path"],
        c.call('dscache.get_uncached_user', 'minio')['pw_uid'],
        c.call('dscache.get_uncached_group', 'minio')['gr_gid'],
    )

    cmd = [
        "sudo", "-E", "-u", "minio",
        "minio", "server",
        "-S", "/usr/local/etc/minio/certs",
        "--address", f'{s3["bindip"]}:{s3["bindport"]}',
        "--console-address", f'{s3["bindip"]}:{s3["console_bindport"]}',
        "--quiet",
        s3["storage_path"],
    ]

    if s3["certificate"]:
        os.environ["MINIO_SERVER_URL"] = f'https://{s3["tls_server_uri"]}:{s3["bindport"]}'

    os.environ["MINIO_ACCESS_KEY"] = s3["access_key"]
    os.environ["MINIO_SECRET_KEY"] = s3["secret_key"]
    if not s3["browser"]:
        os.environ["MINIO_BROWSER"] = "off"

    os.execv(
        b"/usr/bin/sudo",
        [arg.encode() for arg in cmd],
    )
